import hilog from '@ohos.hilog'
// import LogManager,{Level} from '../../webService/services/log/LogManager'

const LOG_DOMAIN = 0x00f101;
const LOG_TAG = 'bledemo';

class Logger {
  debug(...args: any[]) {
    hilog.debug(LOG_DOMAIN, LOG_TAG, this.getFormat(args.length, 'private'), args)
    // LogManager.add(args.join(' '),Level.DEBUG)
  }

  info(...args: any[]) {
    hilog.info(LOG_DOMAIN, LOG_TAG, this.getFormat(args.length), args)
    // LogManager.add(args.join(' '),Level.INFO)
  }

  warn(...args: any[]) {
    hilog.warn(LOG_DOMAIN, LOG_TAG, this.getFormat(args.length), args)
    // LogManager.add(args.join(' '),Level.WARN)
  }

  error(...args: any[]) {
    hilog.error(LOG_DOMAIN, LOG_TAG, this.getFormat(args.length), args)
    // LogManager.add(args.join(' '),Level.ERROR)
  }

  fatal(...args: any[]) {
    hilog.fatal(LOG_DOMAIN, LOG_TAG, this.getFormat(args.length), args)
  }

  getFormat(argLength: number, mark = 'public'): string {
    return `%{${mark}}s, `.repeat(argLength).replace(/,\s$/g, '');
  }

}

const Log = new Logger();
const keys: string[] = ['debug', 'info', 'warn', 'error', 'fatal'];

keys.forEach((key: string) => {
  Log[key] = new Proxy(Log[key], {
    apply(target, thisBinding, args) {
      // const level: string = key[0].toLocaleUpperCase();
      return target.apply(thisBinding, args);
    },
  })
});

const toString = (v): string => typeof v === 'object' ? JSON.stringify(v) : v;


export function logger(tag: string) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = function (...args) {
      const prefix = `${tag}, ${propertyKey}`;
      Log.debug(prefix, 'arguments: ' + JSON.stringify(args));
      const result = original.call(this, ...args);
      if (result !== undefined) {
        if (result instanceof Promise) {
          result.then(res => {
            Log.debug(prefix, 'return: ' + toString(res));
          });
        } else {
          Log.debug(prefix, 'return: ' + toString(result));
        }
      }
      return result;
    }
  }
}


export default Log